package com.headmaster.wap.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import net.sf.json.JSONObject;

/**
 * HttpClient工具类.
 */
public class HttpClientUtil {

    static Logger log = Logger.getLogger(HttpClientUtil.class);

    /** 默认编码格式 */
    public static final String DEFAULT_CHARSET = "UTF-8";

    /** 状态相关 */
    public static final int HTTP_OK_1 = 200;
    public static final int HTTP_OK_2 = 201;
    public static final int TIME_OUT = 60000;

    /** 方法相关 */
    public static final String METHOD_POST = "POST";
    public static final String METHOD_GET = "GET";
    public static final String METHOD_DELETE = "DELETE";

    /** 请求头相关 */
    public static final String JSON_TYPE = "application/json";
    public static final String OCTET_STREAM_TYPE = "application/octet-stream";
    public static final String TEXT_HTML_TYPE = "text/html";


    public static String execute(String url, Map<String, String> paraMap, String method) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet get = null;
        HttpPost post = null;
        Set<Map.Entry<String, String>> entrySet = null;
        if (paraMap != null) {
            entrySet = paraMap.entrySet();
        }

        if ("post".equalsIgnoreCase(method)) {
            post = new HttpPost(url);
            List<NameValuePair> formparams = new ArrayList();
            for (Map.Entry<String, String> entry : entrySet) {
                formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            post.setEntity(urlEntity);

        } else {
            String paraStr = "";
            if (entrySet.size() > 0) {
                paraStr = "?";
                for (Map.Entry<String, String> entry : entrySet) {
                    paraStr = paraStr + entry.getKey() + "=" + entry.getValue() + "&";
                }
            }

            System.out.println(url + paraStr);
            get = new HttpGet(url + paraStr);
        }

        CloseableHttpResponse response = null;
        if ("post".equalsIgnoreCase(method)) {
            response = client.execute(post);
        } else {
            response = client.execute(get);
        }
//        BufferedReader in = new BufferedReader(new InputStreamReader(response
//                .getEntity().getContent()));
//        StringBuffer sb = new StringBuffer("");
//        String line;
//        while ((line = in.readLine()) != null) {
//            sb.append(line);
//        }
//        in.close();
//        String content = sb.toString();
//        return content;
        HttpEntity entity = response.getEntity();    
        if (entity != null) {
            InputStream instreams = entity.getContent();
            String str = convertStreamToString(instreams);
            return str;
        }  
        return null;
    }

	public static String convertStreamToString(InputStream is) {
		StringBuilder sb1 = new StringBuilder();
		byte[] bytes = new byte[4096];
		int size = 0;
		try {      
			while ((size = is.read(bytes)) > 0) {
				String str = new String(bytes, 0, size, "UTF-8");
				sb1.append(str);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
			   e.printStackTrace();
			}
		}
		return sb1.toString();
	}
    /**
     * POST请求
     *
     * @param inputUrl
     * @param params
     * @throws IOException
     * @author 雷传盛
     */
    public static void HttpPOST(String inputUrl, String params) throws IOException {
        URL url = new URL(inputUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(TIME_OUT);
        conn.setReadTimeout(TIME_OUT);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod(METHOD_POST);
//        conn.setRequestProperty(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
//        conn.setRequestProperty(HTTP.CONTENT_ENCODING, DEFAULT_CHARSET);
//        conn.setRequestProperty(HTTP.CONTENT_LEN, String.valueOf(params.length()));
//        conn.setRequestProperty(HTTP.CONTENT_TYPE, OCTET_STREAM_TYPE);
        
        conn.setRequestProperty("Connection", "Keep-Alive");
		conn.setRequestProperty("Charset", "UTF-8");
		conn.setRequestProperty("Content-Length",String.valueOf(params.length()));
		conn.setRequestProperty("Content-Type","application/octet-stream");
        conn.connect();

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.write(params.getBytes(DEFAULT_CHARSET));
        dos.flush();
        dos.close();

        int responseCode = conn.getResponseCode();
        if (responseCode == HTTP_OK_1 || responseCode == HTTP_OK_2) {
            String response = getResponse(conn.getInputStream());
            JSONObject json = JSONObject.fromObject(response);
            if (null != json.get("created")) {
                System.out.println(inputUrl + ", result: " + json.getString("created"));
            }
        } else {
            System.out.println(responseCode);
            String response = getResponse(conn.getInputStream());
            System.out.println("连接失败，response[" + response + "]");
        }
    }

    /**
     * post请求有返回数据
     * @author pengxiaochun
     * @param inputUrl
     * @param params
     * @return
     * @throws IOException
     */
    public static String HttpPOST2(String inputUrl, String params) throws IOException {
        URL url = new URL(inputUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(TIME_OUT);
        conn.setReadTimeout(TIME_OUT);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod(METHOD_POST);
        
        conn.setRequestProperty("Connection", "Keep-Alive");
		conn.setRequestProperty("Charset", "UTF-8");
		conn.setRequestProperty("Content-Length",String.valueOf(params.length()));
		conn.setRequestProperty("Content-Type","application/octet-stream");
        conn.connect();

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.write(params.getBytes(DEFAULT_CHARSET));
        dos.flush();
        dos.close();

        int responseCode = conn.getResponseCode();
        String response;
        if (responseCode == HTTP_OK_1) {
            response = getResponse(conn.getInputStream());
        } else {
            response = getResponse(conn.getInputStream());
            log.error("Error when Http Get for responseCode[" + responseCode + "], response[" + response + "]");
            return null;
        }
        return response;
    }
    
    public static void HttpDelete(String inputUrl) throws IOException {
        URL url = new URL(inputUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(TIME_OUT);
        conn.setReadTimeout(TIME_OUT);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod(METHOD_DELETE);
        conn.setRequestProperty(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
        conn.setRequestProperty(HTTP.CONTENT_ENCODING, DEFAULT_CHARSET);
        conn.setRequestProperty(HTTP.CONTENT_TYPE, OCTET_STREAM_TYPE);
        conn.connect();

        int responseCode = conn.getResponseCode();
        if (responseCode == HTTP_OK_1 || responseCode == HTTP_OK_2) {
            String response = getResponse(conn.getInputStream());
            log.info("Connected successfully, response[" + response + "]");
        } else {
            String response = getResponse(conn.getInputStream());
            System.out.println("连接失败，response[" + response + "]");
        }
    }

    protected static String getResponse(InputStream inStream) throws UnsupportedEncodingException{
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int len = -1;
        byte[] buffer = new byte[1024];
        try {
        	while ((len = inStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(null != inStream) {
					inStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
        byte[] data = outputStream.toByteArray();
        try {
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
        return new String(data, DEFAULT_CHARSET);
    }

    public static String httpGET(String inputUrl) throws IOException {
        URL url = new URL(inputUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(TIME_OUT);
        conn.setReadTimeout(TIME_OUT);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod(METHOD_GET);
        conn.setRequestProperty(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
        conn.setRequestProperty(HTTP.CONTENT_ENCODING, DEFAULT_CHARSET);
        conn.setRequestProperty(HTTP.CONTENT_TYPE, OCTET_STREAM_TYPE);
        conn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
        conn.connect();

        int responseCode = conn.getResponseCode();
        String response;
        if (responseCode == HTTP_OK_1) {
            response = getResponse(conn.getInputStream());
        } else {
            response = getResponse(conn.getInputStream());
            log.error("Error when Http Get for responseCode[" + responseCode + "], response[" + response + "]");
            return null;
        }
        return response;
    }

    public static String toQueryString(Map<?, ?> data) throws UnsupportedEncodingException {
        StringBuffer queryString = new StringBuffer();
        for (Entry<?, ?> pair : data.entrySet()) {
            queryString.append(pair.getKey() + "=");
            queryString.append(URLEncoder.encode((String) pair.getValue(), DEFAULT_CHARSET) + "&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }
        return queryString.toString();
    }


    /**
     * GET请求并返回执行结果
     *
     * @param inputUrl
     * @throws IOException
     * @author 雷传盛
     */
    public static String getResponseFromHttpGET(String inputUrl) throws IOException {
        URL url = new URL(inputUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(TIME_OUT);
        conn.setReadTimeout(TIME_OUT);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod(METHOD_GET);
        conn.setRequestProperty(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
        conn.setRequestProperty(HTTP.CONTENT_ENCODING, DEFAULT_CHARSET);
        conn.setRequestProperty(HTTP.CONTENT_TYPE, OCTET_STREAM_TYPE);
        conn.connect();

        int responseCode = conn.getResponseCode();
        if (responseCode == HTTP_OK_1) {
            String response = getResponse(conn.getInputStream());
            return response;
        } else {
            String response = getResponse(conn.getInputStream());
            System.out.println("连接失败，response[" + response + "]");
        }
        conn.disconnect();
        return null;
    }

    /**
     * Post Json to Url.
     * @param url Url
     * @param json Json String
     * @return String
     * @throws Exception
     */
    public static String postJson(String url, JSONObject json) throws Exception {
    	CloseableHttpClient client = HttpClients.createDefault();
    	CloseableHttpResponse response = null;
    	try {
            
            HttpPost method = new HttpPost(url);
            StringEntity entity = new StringEntity(json.toString(), DEFAULT_CHARSET);
            entity.setContentEncoding(DEFAULT_CHARSET);
            entity.setContentType(JSON_TYPE);
            method.setEntity(entity);
            response = client.execute(method);
        } catch (Exception e) {
            log.error("Error: Post url = " + url + ", json = " + json.toString(), e);
            throw e;
        } finally {
        	if(null != client) {
        		client.close();
        	}
        }
    	return EntityUtils.toString(response.getEntity());
    }


	   public static String doPost(String url, String content) throws IOException {
    	HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        StringEntity entity = new StringEntity(content, "UTF-8");
        post.setEntity(entity);
        return httpClient.execute(post, new BasicResponseHandler());
    }
    
	   /**
		 * GET请求
		 * @author 雷传盛
		 * @param inputUrl
		 * @throws IOException
		 */
		public static String httpGET(String inputUrl, String params) throws IOException {
			System.out.println("inputUrl：" + inputUrl);
			System.out.println("params：" + params);
			URL url = new URL(inputUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(TIME_OUT);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod(METHOD_GET);
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type","application/octet-stream");
			conn.connect();
			
			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
			dos.write(params.getBytes("UTF-8"));
			dos.flush();
			dos.close();
			
			int responseCode = conn.getResponseCode();
			String response = "";
			if (responseCode == HTTP_OK_1) {
				response = getResponse2(conn.getInputStream());
			} else {
				response = getResponse2(conn.getInputStream());
				System.out.println("连接失败，response["+response+"]");
			}
			return response;
		}
		
		private static String getResponse2(InputStream inStream) throws IOException {
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			int len = -1;
			byte[] buffer = new byte[1024];
			while ((len = inStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, len);
			}
			inStream.close();
			byte[] data = outputStream.toByteArray();
			outputStream.close();
			return new String(data, "UTF-8");
		}
	   
	public static void main(String[] args) throws Exception{
		HashMap<String,String> map = new HashMap<String,String>();
//		map.put("appid", "a0e37d579c");
//		map.put("id", "10018");
//		map.put("timestamp", "1441342695");
//		map.put("sign", "da259d6847319b941aa49aa7a8f2e6c3");
		map.put("districtId", "12");
		//String result = HttpClientUtil.execute("http://www.1001fang.com/cdapi/query",map, "post");






		
		String result = HttpClientUtil.execute("http://sh.mogoroom.com/mogoroom-renter/flats/getRoomsDetailByCriteria",map, "post");
		
		System.out.println(result);
	}
	
	public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {  
        JSONObject jsonObject = null;  
        StringBuffer buffer = new StringBuffer();  
        try {  
  
            URL url = new URL(requestUrl);  
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            // 设置请求方式（GET/POST）  
            httpUrlConn.setRequestMethod(requestMethod);  
  
            if ("GET".equalsIgnoreCase(requestMethod))  
                httpUrlConn.connect();  
  
            // 当有数据需要提交时  
            if (null != outputStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();  
                // 注意编码格式，防止中文乱码  
                outputStream.write(outputStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  
  
            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  
            jsonObject = JSONObject.fromObject(buffer.toString());  
        } catch (ConnectException ce) {  
            log.error("Weixin server connection timed out.");  
        } catch (Exception e) {  
            log.error("https request error:{}", e);  
        }  
        return jsonObject;  
    } 
}
